//
//  TextComposeViewController.m
//  SocialChair
//
//  Created by Kelly Heffner Wilkerson on 9/30/10.
//  Copyright 2010 Decipher Media, LLC. All rights reserved.
//

#import "TextComposeViewController.h"


@implementation TextComposeViewController

#pragma mark -
#pragma mark Waiting message management
-(void)setBatchNumber:(int)n {
	batchNum = n;
	
	batchIndicator.text = [NSString stringWithFormat:@"batch %d.", n+1];
}

-(void)setNumberBatches:(int)batches andNumberRecipients:(int)recipients {
	numBatches.text = [NSString stringWithFormat:@"%d batches.  About to show", batches];
	numRecipients.text = [NSString stringWithFormat:@"Sending to %d recipients in", recipients];
}

#pragma mark -
#pragma mark Initialization

-(void)setupWithGroupID:(int)num fromList:(TextLists*)list {
	groupID = num;
	theLists = list;
	[self setBatchNumber:-1];
	
	self.title = [NSString stringWithFormat:@"Text for %@", [theLists getListNameAtIndex:num]];
	composingIndicator.hidden = YES;
	composingIndicator.alpha = 0.0;
	
	if ([MFMessageComposeViewController canSendText]) {
		sendButton.enabled = YES;
	} else {
		sendButton.enabled = NO;
	}
}

+(TextComposeViewController*)newGroupEditWithGroupNum:(int)groupNum fromList:(TextLists*)list {
	NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TextCompose" owner:self options:nil];
	TextComposeViewController *retVal = (TextComposeViewController *)[nib objectAtIndex:0];
	[retVal setupWithGroupID:groupNum fromList:list];
	return retVal;
}

#pragma mark -
#pragma mark Send text
-(void)finishedComposing {
	composingIndicator.hidden = YES;
	composingIndicator.alpha = 0;
	[self setBatchNumber:-1];
	
	if ([MFMessageComposeViewController canSendText]) {
		sendButton.enabled = YES;
	} else {
		sendButton.enabled = NO;
	}
}

-(void)doBatch {
	int batchSize = singleMessageSwitch.on ? 1 : 10;
	
	NSArray *numberList = [theLists getNumbersForGroup:groupID];
	
	if ( batchNum * batchSize < [numberList count]) {
		int remaining = [numberList count] - batchNum * batchSize;
		NSRange range;
		range.location = batchNum * batchSize;
		range.length = remaining >= batchSize ? batchSize : remaining; 
		NSArray *thisBatch = [numberList subarrayWithRange:range];
		
		MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init];
		messageController.messageComposeDelegate = self;
		messageController.body = messageCompose.text;
		messageController.recipients = thisBatch;
		[self presentModalViewController:messageController animated:YES];
	} else {
		[self finishedComposing];
	}
}

- (void)animationFinished:(NSString *)animationID finished:(BOOL)finished context:(void *)context {
	[self doBatch];
}

-(IBAction)sendPressed {
	[messageCompose resignFirstResponder];
	
	[self setBatchNumber:0];
	sendButton.enabled = NO;
	
	int batchSize = singleMessageSwitch.on ? 1 : 10;
	NSArray *numberList = [theLists getNumbersForGroup:groupID];
	float batchCount = (float)[numberList count]/batchSize;
	[self setNumberBatches:(int)ceil(batchCount) andNumberRecipients:[numberList count]];

	
	[UIView beginAnimations:@"beginPlainWaiting" context:nil];
	[UIView setAnimationDuration:0.1];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
	composingIndicator.hidden = NO;
	composingIndicator.alpha = 0.85;
	[UIView commitAnimations];
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
	[self setBatchNumber:batchNum + 1];
	[self dismissModalViewControllerAnimated:YES];
	
	switch (result) {
		case MessageComposeResultSent:
			//handled by viewDidAppear
			break;
		case  MessageComposeResultFailed:
		default:
			[self finishedComposing];
			break;
	}
}

-(void)viewDidAppear:(BOOL)animated {
	if (batchNum >= 0) {
		[self doBatch];
	} else {
		[messageCompose becomeFirstResponder];
	}
}

#pragma mark -
#pragma mark TextView management
- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
	return YES;
}

- (void)textViewDidChange:(UITextView *)textView {
	int length = [textView.text length];
	
	if (length == 1) {
		charCountLabel.text = @"1 character";
	} else {
		charCountLabel.text = [NSString stringWithFormat:@"%d characters", length];
	}
}



#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

